const action = require('../action');
const apiPrefix = require('../config').apiPrefix;
const APIError = require('../module/rest').APIError;

module.exports = {
    'GET /api/table-list': async (ctx, next) => {
        let returnData = await action.table.getAll();
        if (returnData.result) {
            ctx.rest({
                "table": returnData.data
            });
        } else {
            throw new APIError("table:not_found", "table not found by id.");
        }
    },

    'GET /api/table/:tableId': async (ctx, next) => {
        // console.log(`get table by id ${ctx.params.tableId} ...`);
        let returnData = await action.table.getById(ctx.params.tableId);
        if (returnData.result) {
            ctx.rest({
                "table": returnData.data
            });
        } else {
            throw new APIError("table:not_found", "table not found by id.");
        }
    },

    'POST /api/table': async (ctx, next) => {
        let returnData = await action.table.create(ctx.request.body.table);
        if (returnData.result) {
            ctx.rest({
                "table": returnData.data
            });
        } else {
            throw new APIError("table:create_failed", "create table failed");
        }
    },

    'DELETE /api/table/:tableId': async (ctx, next) => {
        let returnData = await action.table.deleteById(ctx.params.tableId);
        if (returnData.result) {
            ctx.rest({
                "result": true
            });
        } else {
            throw new APIError("table:delete_failed", "delete table failed");            
        }
    },

    'PUT /api/table/:tableId/struct': async (ctx, next) => {
        let returnData = await action.table.updateStructById(ctx.params.tableId, ctx.request.body.struct);
        if (returnData.result) {
            ctx.rest({
                "result": true
            });
        } else {
            throw new APIError("table:update_failed", "table not updated");
        }
    },

    'PUT /api/table/:tableId/title': async (ctx, next) => {
        let returnData = await action.table.updateTitleById(ctx.params.tableId, ctx.request.body.title);
        if (returnData.result) {
            ctx.rest({
                "result": true
            });
        } else {
            throw new APIError("table:update_failed", "table not updated");
        }
    },

    'PUT /api/table/:tableId/info': async (ctx, next) => {
        let returnData = await action.table.updateInfoById(ctx.params.tableId, ctx.request.body.info);
        if (returnData.result) {
            ctx.rest({
                "result": true
            });
        } else {
            throw new APIError("table:update_failed", "table not updated");
        }
    },


};